package com.xukun.changgou.gateway.utils;

import com.alibaba.fastjson.JSON;
import com.xukun.changgou.common.response.ResponseEnum;
import com.xukun.changgou.common.response.ResponseUtil;
import com.xukun.changgou.common.response.exception.BaseException;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author xukun
 * @Date 2021-06-04 10:45
 * @Description 自定义的用于网关异常响应工具类
 */
public class ServerHttpUtil {

    public static Mono<Void> doReturn(ServerHttpResponse response, boolean flag, String message) {
        byte[] bits;
        if (flag) {
            bits = JSON.toJSONString(ResponseUtil.success(message, null)).getBytes(StandardCharsets.UTF_8);
        } else {
            bits = JSON.toJSONString(ResponseUtil.fail(message)).getBytes(StandardCharsets.UTF_8);
        }
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    public static Mono<Void> doReturn(ServerHttpResponse response, boolean flag, ResponseEnum responseEnum) {
        byte[] bits;
        if (flag) {
            bits = JSON.toJSONString(ResponseUtil.success(responseEnum)).getBytes(StandardCharsets.UTF_8);
        } else {
            bits = JSON.toJSONString(ResponseUtil.fail(responseEnum)).getBytes(StandardCharsets.UTF_8);
        }
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    public static Mono<Void> doReturn(ServerHttpResponse response, boolean flag, ResponseEnum responseEnum, Object data) {
        byte[] bits;
        if (flag) {
            bits = JSON.toJSONString(ResponseUtil.success(responseEnum, data)).getBytes(StandardCharsets.UTF_8);
        } else {
            bits = JSON.toJSONString(ResponseUtil.fail(responseEnum, data)).getBytes(StandardCharsets.UTF_8);
        }
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    public static Mono<Void> doReturn(ServerHttpResponse response, BaseException exception) {
        byte[] bits = JSON.toJSONString(ResponseUtil.fail(exception.getCode(), exception.getMsg())).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
